#include "libxluploader.h"
#include <assert.h>
#include <iostream>

//////////////////////////////////////////////////////////////////////////
// HTML
HtmlDom html_load (const std::string &html) {
	using namespace htmlcxx;
	HTML::ParserDom parser;
	return parser.parseTree(html);
}

HtmlNodeIter html_get_node_by_tag (HtmlDom &dom, const std::string &tag, int index) {
	int pos = -1;
	HtmlDom::iterator it, end = dom.end();
	for (it = dom.begin(); it != end; ++ it) {
		if (_stricmp(it->tagName().c_str(), tag.c_str()) == 0) {
			++ pos;
			if (pos == index) {
				return it;
			}
		}
	}

	return end;
}

HtmlNodeIterArray html_get_nodes_by_tag (const HtmlDom &dom, const std::string &tag) {
	HtmlNodeIterArray arr;
	HtmlDom::iterator it, end = dom.end();
	for (it = dom.begin(); it != end; ++ it) {
		if (_stricmp(it->tagName().c_str(), tag.c_str()) == 0) {
			arr.push_back(it);
		}
	}

	return arr;
}

HtmlNodeIter html_get_node_by_id (HtmlDom &dom, const std::string &id) {
	HtmlDom::iterator it, end = dom.end();
	for (it = dom.begin(); it != end; ++ it) {
		it->parseAttributes();
		if (_stricmp(it->attribute("id").second.c_str(), id.c_str()) == 0) {
			return it;
		}
	}

	return end;
}

HtmlNodeIterArray html_get_children (HtmlDom &dom, HtmlNodeIter &parent, const std::string &tag) {
	HtmlNodeIterArray arr;
	HtmlNodeIter it = dom.begin(parent), end = dom.end(parent);
	while (it != end) {
		if (tag.length() > 0) {
			if (_stricmp(it->tagName().c_str(), tag.c_str()) == 0) {
				arr.push_back(it);
			}
		} else {
			arr.push_back(it);
		}
		++ it;
	}

	return arr;
}

HtmlNodeIterArray html_get_children_by_id (HtmlDom &dom, const std::string &id, const std::string &tag) {
	HtmlNodeIter itParent = html_get_node_by_id(dom, id);
	if (itParent != dom.end()) {
		return html_get_children(dom, itParent, tag);
	}

	return HtmlNodeIterArray();
}



